import auth from '@/plugins/auth';
import router, { constantRoutes, dynamicRoutes } from '@/router';
import userStore from './user';

const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: []
  }),
  actions: {
    setRoutes(routes) {
      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);
    },
    generateRoutes() {
      return new Promise(resolve => {
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
        asyncRoutes.forEach(route => router.addRoute(route));
        this.setRoutes(asyncRoutes);
        resolve(this.routes);
      });
    }
  }
});

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const userState = userStore();
  const userRoles = userState.roles;
  const userPermissions = userState.permissions;
  const res = [];
  routes.forEach(route => {
    const routePermis = route.permis || {};
    const routeRoles = Object.keys(routePermis);

    // 判断权限
    let roleFlag = false;
    if (routeRoles?.length) {
      // 该菜单需要角色权限
      routeRoles.forEach(routeRole => {
        if (!userRoles.includes(routeRole)) return;
        // 命中该角色
        const routePermissions = routePermis[routeRole];
        if (!routePermissions.length) roleFlag = true;
        routePermissions.forEach(code => {
          if (userPermissions.includes(code)) roleFlag = true;
        });
      });
    } else {
      // 该菜单不需要角色权限
      roleFlag = true;
    }

    // 不满足权限
    if (!roleFlag) return;

    // 递归子集
    if (route.children?.length) {
      route.children = filterDynamicRoutes(route.children);
    }

    // 有children字段，但是没有具体的值，说明有子集但是都没有权限，故不显示
    if (route.children && !route.children.length) return;

    res.push(route);
  });
  return res;
}

export default usePermissionStore;
